package com.wosiliujing.learning.config;

import com.wosiliujing.learning.component.SecurityUserAuthenticationConverter;
import com.wosiliujing.learning.component.PermitAllUrlProperties;
import com.wosiliujing.learning.component.ResourceAuthExceptionEntryPoint;
import lombok.AllArgsConstructor;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @author: liujing
 * @date: 2019/5/1 23:15
 * @description:
 */
@AllArgsConstructor
public class LearningResourcesServerConfigureAdapter extends ResourceServerConfigurerAdapter {
    private final RemoteTokenServices tokenServices;
    private final PermitAllUrlProperties permitAllUrlProperties;
    private final ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint;
    @Bean
    @Primary
    @LoadBalanced
    public RestTemplate lbRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) {
                    super.handleError(response);
                }
            }
        });
        return restTemplate;
    }

    /**
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        /**
         * 允许iframe嵌套，activity在线编辑以及swagger有涉及到
         */
        http.headers().frameOptions().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>
                .ExpressionInterceptUrlRegistry registry = http
                .authorizeRequests();
        /**
         * 放行配置文件配置的url
         */
        permitAllUrlProperties.getIgnoreUrls()
                .forEach(url -> registry.antMatchers(url).permitAll());
        registry.anyRequest().authenticated()
                .and().csrf().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        SecurityUserAuthenticationConverter userAuthenticationConverter = new SecurityUserAuthenticationConverter();
        accessTokenConverter.setUserTokenConverter(userAuthenticationConverter);
        tokenServices.setRestTemplate(lbRestTemplate());
        tokenServices.setAccessTokenConverter(accessTokenConverter);
        resources
                .tokenServices(tokenServices)
                .authenticationEntryPoint(resourceAuthExceptionEntryPoint);
    }
}
